﻿using _15Net8AspNetCore_ORM.Context;
using _15Net8AspNetCore_ORM.Models;
using Dapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace _15Net8AspNetCore_ORM.OrderRespository
{
    public class OrderEFCoreRespository : IOrderRespository
    {
        public EFCoreDBContext _EFCoreDB { get; set; }
        public OrderEFCoreRespository(EFCoreDBContext eFCoreDB)
        {
            _EFCoreDB = eFCoreDB;
        }

        public Order AddOrder(Order order)
        {
            _EFCoreDB.Order.Add(order);
            _EFCoreDB.SaveChanges();
            return order;
        }

        public void DeleteOrder(int id)
        {
            Order Order = _EFCoreDB.Order.FirstOrDefault(T => T.Id == id);
            if (Order != null)
            {
                _EFCoreDB.Order.Remove(Order);
                _EFCoreDB.SaveChangesAsync();
            }
        }

        public List<Order> GetAllOrder()
        {
            // 1、创建链接
            List<Order> orders = _EFCoreDB.Order.ToList();
            return orders;
        }

        public Order GetOrder(int id)
        {
            Order order = _EFCoreDB.Order.FirstOrDefault(T => T.Id == id);

            return order;
        }

        public void UpdateOrder(int id, Order order)
        {
            #region
            //// 1. 检查实体是否已被上下文跟踪
            //var entry = _EFCoreDB.Entry(Order);
            //if (entry.State == EntityState.Detached)
            //{
            //    // 未跟踪：附加实体并标记为修改
            //    _EFCoreDB.Attach(Order);
            //    entry.State = EntityState.Modified;
            //}
            //else
            //{
            //    // 已跟踪：直接标记为修改
            //    entry.State = EntityState.Modified;
            //}
            //// 2. 保存变更
            //_EFCoreDB.SaveChanges();
            #endregion


            // 1. 查询数据库中的实体
            var existingOrder = _EFCoreDB.Order.FirstOrDefault(T => T.Id == id);
            if (existingOrder == null)
            {
                throw new KeyNotFoundException("订单不存在");
            }

            // 2. 复制更新的属性
            _EFCoreDB.Entry(existingOrder).CurrentValues.SetValues(order);

            // 3. 保存变更
            _EFCoreDB.SaveChanges();


            ////1、设置更新状态
            //_EFCoreDB.Entry(Order).State = EntityState.Modified;
            //try
            //{
            //    _EFCoreDB.SaveChanges();
            //}
            //catch (Exception)
            //{
            //    throw;
            //}
        }

    }
}
